package main

import (
	"fmt"

	"time"

	"sync"

	"os"

	"github.com/gorilla/websocket"
)

var wsNum int
var connectErrorNum int
var readErrNum int
var mutex sync.Mutex

//const ip = "127.0.0.1"
var socket = "127.0.0.1:8001"

func read(username string, conn *websocket.Conn) {
	mutex.Lock()
	wsNum++
	mutex.Unlock()
	defer func() {
		mutex.Lock()
		wsNum--
		mutex.Unlock()
	}()
	var err error
	msg := make([]byte, 1024)
	for {
		_, msg, err = conn.ReadMessage()
		if err != nil {
			fmt.Println(username, "read error:", err.Error())
			readErrNum++
			return
		}
		fmt.Println(string(msg))
	}
}

func wsLogin(username string) {
	conn, resp, err := websocket.DefaultDialer.Dial("ws://"+socket+"/wsLogin?account="+username+"&password=123456", nil)
	if err != nil {
		fmt.Println("connect error:", err.Error())
		connectErrorNum++
		return
	}
	fmt.Println("resp:", resp)
	read(username, conn)
}
func main() {
	fmt.Println(os.Args)
	if len(os.Args) < 3 {
		fmt.Println("启动参数有误")
		return
	}
	if len(os.Args) == 4 {
		socket = os.Args[3]
	}
	wsNum = 0
	connectErrorNum = 0
	readErrNum = 0
	var i, num int64
	base := int64(1e10 + 1e8 + 8)
	_, err := fmt.Sscan(os.Args[1], &i)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	_, err = fmt.Sscan(os.Args[2], &num)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	fmt.Println("login", "account", i+base, "to", num+base)
	for ; i <= num; i++ {
		time.Sleep(time.Microsecond * 100)
		go wsLogin(fmt.Sprint(i + base))
	}
	for {
		fmt.Println("wsConnect num:", wsNum,
			"connectErrorNum:", connectErrorNum,
			"readErrNum:", readErrNum)
		time.Sleep(time.Second * 10)
	}
}
